package com.longqin.business.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.longqin.business.config.RequiredPermission;
import com.longqin.business.entity.BusExamine;
import com.longqin.business.entity.BusRequirement;
import com.longqin.business.entity.WfNode;
import com.longqin.business.feign.FeignService;
import com.longqin.business.service.IBusExamineService;
import com.longqin.business.service.IBusRequirementService;
import com.longqin.business.service.IWfWorkService;
import com.longqin.business.util.ResponseData;
import com.longqin.business.util.ResponseEnum;
import com.longqin.business.util.SessionUtil;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * <p>
 * 需求管理 前端控制器
 * </p>
 *
 * @author longqin
 * @since 2024-12-23
 */
@RestController
@RequestMapping("/requirement")
public class BusRequirementController {

	@Autowired
	IBusRequirementService busRequirementService;
	
	@Autowired
	IBusExamineService busExamineService;
	
	@Autowired
	IWfWorkService wfWorkService;
	
	@Autowired
	FeignService feignService;
	
	@Value("${requirement-flow-id}")
	public int FLOW_ID;
	
	private static final String REQUIREMENT_TABLE_NAME = "bus_requirement";
	private static final String EXAMINE_TABLE_NAME = "bus_examine";
	
	/**
	 * @Description 获取单个需求
	 * @Author longqin
	 * @Time: 2024年12月23日
	 */
	@ApiOperation(value = "获取单个需求", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "需求ID", required = true, dataType = "int") })
	@ApiResponses({ @ApiResponse(code = 1, message = "查询成功"), @ApiResponse(code = 0, message = "查询失败") })
	@GetMapping("/getById")
	public ResponseData getById(int id) {
		BusRequirement requirement = busRequirementService.getById(id);
		return new ResponseData(ResponseEnum.SUCCESS.getCode(), "查询成功", requirement);
	}
	
	/**
	 * @Description 分页获取需求清单
	 * @Author longqin
	 * @Time: 2024年12月23日
	 */
	@ApiOperation(value = "分页获取需求清单", httpMethod = "GET")
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "status", value = "状态", required = false, dataType = "Integer"),
		@ApiImplicitParam(name = "title", value = "需求标题", required = true, dataType = "String"),
		@ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int"),
		@ApiImplicitParam(name = "size", value = "每页数量", required = true, dataType = "int") })
	@ApiResponses({ @ApiResponse(code = 1, message = "查询成功"), @ApiResponse(code = 0, message = "查询失败"), @ApiResponse(code = 3, message = "参数错误") })
	@GetMapping("/getRequirementPage")
	@RequiredPermission("requirement:view")
	public ResponseData getRequirementPage(Integer status, String title, Integer page, Integer size) {
		if (null == page || null == size) {
			return new ResponseData(ResponseEnum.BADPARAM.getCode(), "参数错误");
		}
		List<BusRequirement> requirementList = busRequirementService.getPage(status, title, SessionUtil.getSessionUser().getOrganizationId(), (page - 1) * size, size);
		int total = busRequirementService.getCount(status, title, SessionUtil.getSessionUser().getOrganizationId());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", requirementList);
		map.put("total", total);
		return new ResponseData(ResponseEnum.SUCCESS.getCode(), "查询成功", map);
	}
	
	/**
	 * @Description 需求发起
	 * @Author longqin
	 * @Time: 2024年12月23日
	 */
	@ApiOperation(value = "需求发起", httpMethod = "POST")
	@ApiImplicitParams({ @ApiImplicitParam(name = "entity", value = "需求实体项", required = true, dataType = "BusRequirement") })
	@ApiResponses({ @ApiResponse(code = 1, message = "提交成功，审批流程已启动"), @ApiResponse(code = 0, message = "提交失败"),
			@ApiResponse(code = 3, message = "参数错误") })
	@PostMapping("/apply")
	@RequiredPermission("requirement:view")
	public ResponseData apply(@RequestBody BusRequirement entity) throws Exception {
		if (null == entity || null == entity.getTitle()) {
			return new ResponseData(ResponseEnum.BADPARAM.getCode(), "参数错误");
		}
		if (entity.getCreator() == null) entity.setCreator(SessionUtil.getSessionUser().getUserId());
		if (entity.getDepartmentId() == null) entity.setDepartmentId(SessionUtil.getSessionUser().getDepartmentId());
		if (entity.getOrganizationId() == null) entity.setOrganizationId(SessionUtil.getSessionUser().getOrganizationId());
		entity.setStatus(1); // 编制状态
		int result = 0;
		if (entity.getId() != null){
			result = busRequirementService.update(entity);
		}
		else{
			result = busRequirementService.create(entity);
		}
		if (result > 0){
			// 启动审批流程
			result = wfWorkService.dealWork(FLOW_ID, entity.getProcessId(), 1, REQUIREMENT_TABLE_NAME, new ArrayList<String>(), new ArrayList<String>(), 
					SessionUtil.getSessionUser().getUserId(), SessionUtil.getSessionUser().getOrganizationId(), false, entity.getId(), entity.getWorkNodes());
			if (result >= 0){
				// 提交成功，更改需求状态为审核中
				entity.setStatus(2); // 审核状态
				busRequirementService.update(entity);
				String nickName = feignService.getNickNameById(result).getData().toString();
				return new ResponseData(ResponseEnum.SUCCESS.getCode(), "提交成功，审批流程已启动", "已发送给审批人：" + nickName);
			}
			else if (result == -2){
				return new ResponseData(ResponseEnum.ERROR.getCode(), "找不到审批人", result);
			}
			else{
				return new ResponseData(ResponseEnum.ERROR.getCode(), "提交失败", result);
			}
		}
		else{
			return new ResponseData(ResponseEnum.ERROR.getCode(), "提交失败", result);
		}
	}
	
	/**
	 * @Description 需求暂存
	 * @Author longqin
	 * @Time: 2024年12月23日
	 */
	@ApiOperation(value = "需求暂存", httpMethod = "POST")
	@ApiImplicitParams({ @ApiImplicitParam(name = "entity", value = "需求实体项", required = true, dataType = "BusRequirement") })
	@ApiResponses({ @ApiResponse(code = 1, message = "暂存成功"), @ApiResponse(code = 0, message = "暂存失败"),
			@ApiResponse(code = 3, message = "参数错误") })
	@PostMapping("/save")
	@RequiredPermission("requirement:view")
	public ResponseData save(@RequestBody BusRequirement entity) throws Exception {
		if (null == entity || null == entity.getTitle()) {
			return new ResponseData(ResponseEnum.BADPARAM.getCode(), "参数错误");
		}
		if (entity.getCreator() == null) entity.setCreator(SessionUtil.getSessionUser().getUserId());
		if (entity.getDepartmentId() == null) entity.setDepartmentId(SessionUtil.getSessionUser().getDepartmentId());
		if (entity.getOrganizationId() == null) entity.setOrganizationId(SessionUtil.getSessionUser().getOrganizationId());
		entity.setStatus(1); // 编制状态
		int result = 0;
		if (entity.getId() != null){
			result = busRequirementService.update(entity);
		}
		else{
			result = busRequirementService.create(entity);
		}
		if (result > 0){
			return new ResponseData(ResponseEnum.SUCCESS.getCode(), "暂存成功", entity.getId());
		}
		else{
			return new ResponseData(ResponseEnum.ERROR.getCode(), "暂存失败", entity.getId());
		}
	}

	/**
	 * @Description 删除需求
	 * @Author longqin
	 * @Time: 2024年12月23日
	 */
	@ApiOperation(value = "删除需求", httpMethod = "POST")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "需求ID", required = true, dataType = "int") })
	@ApiResponses({ @ApiResponse(code = 1, message = "删除成功"), @ApiResponse(code = 0, message = "删除失败") })
	@PostMapping("/delete")
	@RequiredPermission("requirement:view")
	public ResponseData delete(int id) throws Exception {
		int result = busRequirementService.delete(id);
		if (result >= 0){
			return new ResponseData(ResponseEnum.SUCCESS.getCode(), "删除成功", result);
		}
		else{
			return new ResponseData(ResponseEnum.ERROR.getCode(), "删除失败", result);
		}
	}
	
	/**
	 * @Description 根据流程实例ID获取需求
	 * @Author longqin
	 * @Time: 2024年1月7日
	 */
	@ApiOperation(value = "根据流程实例ID获取需求", httpMethod = "GET")
	@ApiImplicitParams({ @ApiImplicitParam(name = "workId", value = "流程实例ID", required = true, dataType = "int") })
	@ApiResponses({ @ApiResponse(code = 1, message = "查询成功"), @ApiResponse(code = 0, message = "查询失败") })
	@GetMapping("/getByWorkId")
	public ResponseData getByWorkId(int workId) {
		BusRequirement requirement = busRequirementService.getByWorkId(workId);
		return new ResponseData(ResponseEnum.SUCCESS.getCode(), "查询成功", requirement);
	}
	
	/**
	 * @Description 需求审批
	 * @Author longqin
	 * @Time: 2024年12月23日
	 */
	@ApiOperation(value = "需求审批", httpMethod = "POST")
	@ApiImplicitParams({ @ApiImplicitParam(name = "entity", value = "审核实体项", required = true, dataType = "BusExamine") })
	@ApiResponses({ @ApiResponse(code = 1, message = "处理成功"), @ApiResponse(code = 0, message = "处理失败"),
			@ApiResponse(code = 3, message = "参数错误") })
	@PostMapping("/examine")
//	@RequiredPermission("requirement:view")
	public ResponseData examine(@RequestBody BusExamine entity) throws Exception {
		if (null == entity || null == entity.getExamineStatus() || null == entity.getContent()) {
			return new ResponseData(ResponseEnum.BADPARAM.getCode(), "参数错误");
		}
		entity.setCreator(SessionUtil.getSessionUser().getUserId());
		entity.setOrganizationId(SessionUtil.getSessionUser().getOrganizationId());
		int result = busExamineService.create(entity);
		if (result > 0){
			// 审批提交
			result = wfWorkService.dealWork(FLOW_ID, entity.getProcessId(), entity.getExamineStatus(), EXAMINE_TABLE_NAME, new ArrayList<String>(), new ArrayList<String>(), 
					SessionUtil.getSessionUser().getUserId(), SessionUtil.getSessionUser().getOrganizationId(), false, entity.getId(), null);
			if (result >= 0){
				BusRequirement requirement = busRequirementService.getByWorkId(entity.getWorkId());
				if (result == 0){ // 结束流程
					// 更改需求状态为发布
					requirement.setStatus(3); // 审核状态
					busRequirementService.update(requirement);
					return new ResponseData(ResponseEnum.SUCCESS.getCode(), "处理成功", "处理成功，流程已结束");
				}
				else{
					if (entity.getExamineStatus() == 0){ //驳回
						// 更改需求状态为编制
						requirement.setStatus(1); // 审核状态
						busRequirementService.update(requirement);
					}
					String nickName = feignService.getNickNameById(result).getData().toString();
					return new ResponseData(ResponseEnum.SUCCESS.getCode(), "处理成功", "已发送给下个处理人：" + nickName);
				}
			}
			else if (result == -2){
				return new ResponseData(ResponseEnum.ERROR.getCode(), "找不到审批人", result);
			}
			else{
				return new ResponseData(ResponseEnum.ERROR.getCode(), "处理失败", result);
			}
		}
		else{
			return new ResponseData(ResponseEnum.ERROR.getCode(), "处理失败", result);
		}
	}
	
	/**
	 * @Description 获取流程节点用于节点配置
	 * @Author longqin
	 * @Time: 2025年1月10日
	 */
	@ApiOperation(value = "获取流程节点", httpMethod = "GET")
	@ApiResponses({ @ApiResponse(code = 1, message = "查询成功"), @ApiResponse(code = 0, message = "查询失败") })
	@GetMapping("/getFlowNodes")
	public ResponseData getFlowNodes() {
		List<WfNode> nodeList = wfWorkService.getFlowNodes(FLOW_ID);
		if (nodeList != null){
			// 剔除开始节点
			List<WfNode> newList = nodeList.stream().filter(s -> s.getGroupSeq() != 1).collect(Collectors.toList());
			return new ResponseData(ResponseEnum.SUCCESS.getCode(), "查询成功", newList);
		}
		else{
			return new ResponseData(ResponseEnum.ERROR.getCode(), "查询失败");
		}
	}
}
